package cn.edu.ujs.coor.service;

import cn.edu.ujs.coor.common.exception.CoorException;
import cn.edu.ujs.coor.model.Field;
import cn.edu.ujs.coor.model.Project;
import cn.edu.ujs.coor.repository.field.FieldRepository;
import cn.edu.ujs.coor.repository.project.ProjectRepository;
import cn.edu.ujs.coor.request.IdRequest;
import cn.edu.ujs.coor.request.field.FieldAddRequest;
import cn.edu.ujs.coor.request.field.FieldUpdateRequest;
import cn.edu.ujs.coor.util.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class FieldService extends BaseService<Field, Field> {

    @Autowired
    private ProjectRepository projectRepository;

    @Autowired
    public void setRepository (FieldRepository repository) {
        this.repository = repository;
    }

    /**
     * 根据项目编号查询字段列表
     * @param projectId
     * @return
     */
    public List<Field> list (String projectId) {
        return ((FieldRepository) repository).findByProjectIdOrderBySortAsc(projectId);
    }

    /**
     * 添加字段
     * @param request
     */
    public void add (FieldAddRequest request) {
        Project project = projectRepository.findById(request.getProjectId()).orElse(null);
        if (project == null) {
            throw new CoorException("项目不存在");
        }
        Field field = Field.builder().build();
        BeanUtil.copyBeanIgnoreNull(field, request);
        this.save(field);
    }

    /**
     * 更新字段
     * @param request
     */
    public void update (FieldUpdateRequest request) {
        Field field = this.findById(request.getId());
        if (field == null) {
            throw new CoorException("该字段不存在");
        }
        this.save(request.copyToEntity(field));
    }

    /**
     * 删除字段
     * @param request
     */
    public void delete (IdRequest request) {
        Field field = this.findById(request.getId());
        if (field == null) {
            throw new CoorException("该字段不存在");
        }
        this.delete(field);
    }
}
